package com.knife.news.stat;

import java.io.IOException;
import java.util.Enumeration;
import java.util.StringTokenizer;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.xy.XYDataset;

@SuppressWarnings("serial")
public class StatServlet
    extends HttpServlet {
    //private static final String CONTENT_TYPE = "text/html; charset=UTF-8";
    private static final String CONTENT_TYPE = "UTF-8";

    //Initialize global variables
    public void init() throws ServletException {
    }

    /**
     * 判断是哪种操作
     * 1，forum_delete：删除讨论区
     * 2，forum_add：新增讨论区
     * 3，forum_update：更新讨论区
     * 4，forum_select：获取讨论区列表
     * 5，forum_view：获取某一个讨论区详细信息
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws
        ServletException, IOException {
    	request.setCharacterEncoding(StatServlet.CONTENT_TYPE);
        String type = request.getParameter("type");
        if (type == null) {
            return;
        }
        else if (type.equalsIgnoreCase("dayStat")) { //每日访问量统计
            dayStat(request, response);
        }
        else if (type.equalsIgnoreCase("monthStat")) { //每月访问量统计
            monthStat(request, response);
        }
        else if (type.equalsIgnoreCase("hourStat")) { //每个时间段访问量统计
            hourStat(request, response);
        }
        else if (type.equalsIgnoreCase("browserStat")) { //客户端浏览器统计
            browserStat(request, response);
        }
        else if (type.equalsIgnoreCase("osStat")) { //客户端操作系统统计
            osStat(request, response);
        }
    }
    /**
     * 处理日流量统计
     * 1，获得要统计多少天的流量
     * 2，调用StatHandle的getDayStat方法，获取数据集
     * 3，将数据集保存在session中
     * 4，如果出现异常，将异常信息保存到request对象中
     * 5，如果操作成功，返回line.jsp页面
     * 6，否则返回error.jsp页面
     */
    private void dayStat(HttpServletRequest request,
                         HttpServletResponse response) {
        boolean isSuccess = false;
        //操作成功失败标记
        try {
            isSuccess = true;
            int count = Integer.parseInt(request.getParameter("dayCounts"));
            //从请求头中获取dayCounts，该参数表示要统计多少天的流量
            XYDataset data = StatHandle.getDayStat(count);
            //调用StatHandle的getDayStat方法从数据库中获取每天的访问次数并保存在数据集中
            request.getSession().setAttribute("dataset", data);
            //将数据集保存在session对象中，便于外部程序使用
        }
        catch (Exception es) {
            es.printStackTrace();
            isSuccess = false;
            request.setAttribute("error", es.getMessage());
            //如果出现异常，将错误信息保存在request对象的error变量中
        }
        String forward = null;
        if (isSuccess) {
            request.removeAttribute("error");
            forward = "/statistics/day.jsp";
            //如果操作成功，流程转至line.jsp页面
        }
        else {
            forward = "/statistics/error.jsp";
            //如果操作失败，流程转至error.jsp页面
        }
        forward(request, response, forward);
        //转发请求
    }

    private void monthStat(HttpServletRequest request,
                           HttpServletResponse response) {
        boolean isSuccess = false;
        try {
            isSuccess = true;
            int count = Integer.parseInt(request.getParameter("monthCounts"));
            DefaultCategoryDataset data = StatHandle.getMonthStat(count);
            request.getSession().setAttribute("dataset", data);
        }
        catch (Exception es) {
            es.printStackTrace();
            isSuccess = false;
            request.setAttribute("error", es.getMessage());
        }
        String forward = null;
        if (isSuccess) {
            request.removeAttribute("error");
            forward = "/statistics/month.jsp";
        }
        else {
            forward = "/statistics/error.jsp";
        }
        forward(request, response, forward);
    }

    private void hourStat(HttpServletRequest request,
                          HttpServletResponse response) {
        boolean isSuccess = false;
        try {
            isSuccess = true;
            int dayCounts = Integer.parseInt(request.getParameter("dayCounts"));
            int count = Integer.parseInt(request.getParameter("count"));
            DefaultCategoryDataset data = StatHandle.getHourStat(dayCounts,
                count);
            request.getSession().setAttribute("dataset", data);
        }
        catch (Exception es) {
            es.printStackTrace();
            isSuccess = false;
            request.setAttribute("error", es.getMessage());
        }
        String forward = null;
        if (isSuccess) {
            request.removeAttribute("error");
            forward = "/statistics/hour.jsp";
        }
        else {
            forward = "/statistics/error.jsp";
        }
        forward(request, response, forward);
    }

    private void osStat(HttpServletRequest request,
                        HttpServletResponse response) {
        boolean isSuccess = false;
        try {
            isSuccess = true;
            DefaultPieDataset data = StatHandle.getosStat();
            request.getSession().setAttribute("dataset", data);
        }
        catch (Exception es) {
            es.printStackTrace();
            isSuccess = false;
            request.setAttribute("error", es.getMessage());
        }
        String forward = null;
        if (isSuccess) {
            request.removeAttribute("error");
            forward = "/statistics/os.jsp";
        }
        else {
            forward = "/statistics/error.jsp";
        }
        forward(request, response, forward);
    }

    private void browserStat(HttpServletRequest request,
                             HttpServletResponse response) {
        boolean isSuccess = false;
        try {
            isSuccess = true;
            DefaultPieDataset data = StatHandle.getbrowserStat();
            request.getSession().setAttribute("dataset", data);
        }
        catch (Exception es) {
            es.printStackTrace();
            isSuccess = false;
            request.setAttribute("error", es.getMessage());
        }
        String forward = null;
        if (isSuccess) {
            request.removeAttribute("error");
            forward = "/statistics/browser.jsp";
        }
        else {
            forward = "/statistics/error.jsp";
        }
        forward(request, response, forward);
    }

    /**
     * 将控制流程转到url所表示的页面
     * @param url String 要转到的页面
     */
    private void forward(HttpServletRequest request,
                         HttpServletResponse response, String url) {
        try {
            request.getRequestDispatcher(response.encodeURL(url)).
                forward(request, response);
        }
        catch (Exception es) {
            es.printStackTrace();
        }
    }

//    127.0.0.1
//    /stat/statservlet
//    HTTP/1.1
//    127.0.0.1
//    127.0.0.1
//    /statservlet
//    127.0.0.1
//    null
//    null
//    /stat
//    type=dayStat&dayCounts=5
//    http://127.0.0.1/stat/statservlet
//    /stat/statservlet

    @SuppressWarnings("rawtypes")
	public static void doGet(HttpServletRequest request) {
        /*
        System.out.println(request.getMethod()); // GET
        System.out.println(request.getRequestURI()); // /stat/statservlet
        System.out.println(request.getProtocol()); // HTTP/1.1
        System.out.println(request.getRemoteAddr()); // 127.0.0.1
        System.out.println(request.getRemoteHost()); // 127.0.0.1

        System.out.println(request.getServletPath()); // 127.0.0.1
        System.out.println(request.getServerName()); // 127.0.0.1
        System.out.println(request.getServerPort()); // 127.0.0.1

        System.out.println(request.getPathInfo()); // 127.0.0.1
        System.out.println(request.getPathTranslated()); // 127.0.0.1
        System.out.println(request.getContextPath()); // 127.0.0.1

        System.out.println(request.getQueryString()); // 127.0.0.1
        System.out.println(request.getRequestURL().toString()); // 127.0.0.1
        System.out.println(request.getRequestURI()); // 127.0.0.1
        */
        Enumeration headerNames = request.getHeaderNames();

        while (headerNames.hasMoreElements()) {
            String headerName = (String) headerNames.nextElement();
            System.out.println(headerName + ":" +request.getHeader(headerName));
        }

        String Agent = request.getHeader("User-Agent");
        StringTokenizer st = new StringTokenizer(Agent, ";");
        st.nextToken();
        //得到用户的浏览器名
        String userbrowser = st.nextToken();
        //得到用户的操作系统名
        String useros = st.nextToken();
        System.out.println("取得的用户信息:"+userbrowser+"."+useros);
    }

//     accept-----*/*
//     accept-language-----zh-cn
//     accept-encoding-----gzip, deflate
//     user-agent-----Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)
//     host-----127.0.0.1
//     connection-----Keep-Alive

}
